<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>PyMOTW: atexit &mdash; PyMOTW Document v1.6 documentation</title>
    <link rel="stylesheet" href="../_static/mytest.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.6',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    
    <!-- comment utility -->
    <link rel="stylesheet" href="../_static/comment.css" type="text/css" />
    <script type="text/javascript" src="../_static/md5.js"></script>
    <script type="text/javascript" src="../_static/comment.js"></script>
    <!-- end -->
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="PyMOTW Document v1.6 documentation" href="../index.html" />
    <link rel="next" title="PyMOTW: collections" href="collections.html" />
    <link rel="prev" title="PyMOTW: commands" href="commands.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="collections.html" title="PyMOTW: collections"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="commands.html" title="PyMOTW: commands"
             accesskey="P">previous</a> |</li>
        <li><a href="../index.html">PyMOTW Document v1.6 documentation</a> &raquo;</li> 
      </ul>
    </div> 
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">PyMOTW: atexit</a><ul>
<li><a class="reference external" href="#id1">描述</a></li>
<li><a class="reference external" href="#id2">示例</a></li>
<li><a class="reference external" href="#atexit">什么时候atexit函数不被调用?</a></li>
<li><a class="reference external" href="#id3">在atexit回调函数中的异常</a></li>
<li><a class="reference external" href="#id4">参考</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="commands.html"
                                  title="previous chapter">PyMOTW: commands</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="collections.html"
                                  title="next chapter">PyMOTW: collections</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/documents/atexit.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div> 

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="pymotw-atexit">
<h1>PyMOTW: atexit<a class="headerlink" href="#pymotw-atexit" title="Permalink to this headline">¶</a></h1>
<ul class="simple">
<li>模块: atexit</li>
<li>目的: 当一程序关闭时, 注册一个需要被调用的函数.</li>
<li>Python版本: 2.1.3+</li>
</ul>
<div class="section" id="id1">
<h2>描述<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>atexit模块提供了一个简单的接口, 一般情况下, 用于注册当程序关闭时需要调用的函数. sys模块虽然也提供了类似功能的钩子, sys.exitfunc, 但是它只能注册一个函数. 而atexit注册表可以被多个模块和库同时使用.</p>
</div>
<div class="section" id="id2">
<h2>示例<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>一个简单的例子, 它通过atexit.register()注册一个函数:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">atexit</span>

<span class="k">def</span> <span class="nf">all_done</span><span class="p">():</span>

    <span class="k">print</span> <span class="s">&#39;all_done()&#39;</span>


<span class="k">print</span> <span class="s">&#39;Registering&#39;</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">all_done</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Registered&#39;</span>
</pre></div>
</div>
<p>由于上面的程序实际上不做任何其他事情, 所以在程序关闭时立即调用了all_done():</p>
<div class="highlight-python"><pre>$ python atexit_simple.py
Registering
Registered
all_done()</pre>
</div>
<p>注册多个函数也是有可能的, 并且可以传递参数给它们. 这在安全地断开数据库连接, 或删除临时文件等情况下, 都是非常有用的. 因为可以将参数传递给注册函数, 所以我们甚至不需要保留一个单独需要清理东西的列表 &#8211; 我们只需要多次注册一个清理函数.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">my_cleanup</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>

    <span class="k">print</span> <span class="s">&#39;my_cleanup(</span><span class="si">%s</span><span class="s">)&#39;</span> <span class="o">%</span> <span class="n">name</span>


<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">my_cleanup</span><span class="p">,</span> <span class="s">&#39;first&#39;</span><span class="p">)</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">my_cleanup</span><span class="p">,</span> <span class="s">&#39;second&#39;</span><span class="p">)</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">my_cleanup</span><span class="p">,</span> <span class="s">&#39;third&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>注意: 这里函数调用的顺序是按照它们注册顺序的逆序的. 这就允许模块按照它们被导入顺序的逆序(由此来注册它们的atexit函数)来清理, 这样可以减少模块间的依赖关系.</p>
<div class="highlight-python"><pre>$ python atexit_multiple.py
my_cleanup(third)
my_cleanup(second)
my_cleanup(first)</pre>
</div>
</div>
<div class="section" id="atexit">
<h2>什么时候atexit函数不被调用?<a class="headerlink" href="#atexit" title="Permalink to this headline">¶</a></h2>
<p>由atexit注册的那些回调函数不会被调用的情况有以下几种:</p>
<blockquote>
<ul class="simple">
<li>程序由于收到信号退出. ## 这个信号是??</li>
<li>直接调用os._exit()</li>
<li>在python解释器中, 检测到很严重的错误.</li>
</ul>
</blockquote>
<p>为了举例程序是通过信号被杀死的, 我们可以修改 subprocess summary 中的一个例子. 这里有2个文件需要被调用, 分别是父进程和子进程:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">signal</span>
<span class="kn">import</span> <span class="nn">subprocess</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="n">proc</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">Popen</span><span class="p">(</span><span class="s">&#39;atexit_signal_child.py&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;PARENT: Pausing before sending signal...&#39;</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;PARENT: Signaling </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">proc</span><span class="o">.</span><span class="n">pid</span>
<span class="n">os</span><span class="o">.</span><span class="n">kill</span><span class="p">(</span><span class="n">proc</span><span class="o">.</span><span class="n">pid</span><span class="p">,</span> <span class="n">signal</span><span class="o">.</span><span class="n">SIGTERM</span><span class="p">)</span>
</pre></div>
</div>
<p>子进程中设置atexit回调函数, 以证明它没有被调用.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">not_called</span><span class="p">():</span>
    <span class="k">print</span> <span class="s">&#39;CHILD: atexit handler should not have been called&#39;</span>

<span class="k">print</span> <span class="s">&#39;CHILD: Registering atexit handler&#39;</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">not_called</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;CHILD: Pausing to wait for signal&#39;</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">5</span><span class="p">)</span>
</pre></div>
</div>
<p>运行之后, 输出信息如下:</p>
<div class="highlight-python"><pre>$ python atexit_signal_parent.py
CHILD: Registering atexit handler
CHILD: Pausing to wait for signal
PARENT: Pausing before sending signal...
PARENT: Signaling 2038</pre>
</div>
<p>注意到子进程中没有调用not_called(), 所以就没有打印出相应的信息.
类似的, 如果一个程序绕过正常的退出路径的话, 它也不会执行atexit回调函数.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">def</span> <span class="nf">not_called</span><span class="p">():</span>

    <span class="k">print</span> <span class="s">&#39;This should not be called&#39;</span>


<span class="k">print</span> <span class="s">&#39;Registering&#39;</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">not_called</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Registered&#39;</span>

<span class="k">print</span> <span class="s">&#39;Exiting...&#39;</span>
<span class="n">os</span><span class="o">.</span><span class="n">_exit</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>
</pre></div>
</div>
<p>由于我们直接调用os._eixt()退出程序, 所以atexit的回调函数不会被调用.</p>
<div class="highlight-python"><pre>$ python atexit_os_exit.py
Registering
Registered
Exiting...</pre>
</div>
<p>如果我们使用sys.exit()的话, atexit的回调函数仍然会被执行.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">def</span> <span class="nf">all_done</span><span class="p">():</span>

    <span class="k">print</span> <span class="s">&#39;all_done()&#39;</span>


<span class="k">print</span> <span class="s">&#39;Registering&#39;</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">all_done</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Registered&#39;</span>

<span class="k">print</span> <span class="s">&#39;Exiting...&#39;</span>
<span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python atexit_sys_exit.py
Registering
Registered
Exiting...
all_done()</pre>
</div>
<p>在Python解释器中模拟出一个严重错误来验证程序的退出也没有调用atexit回调函数,,,这个就留给读者了吧. :-)</p>
</div>
<div class="section" id="id3">
<h2>在atexit回调函数中的异常<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p>在atexit回调函数中引发异常后的回溯信息会被输出到控制台, 最后引发的异常会重新被抛出以作为程序的最终错误信息.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">exit_with_exception</span><span class="p">(</span><span class="n">message</span><span class="p">):</span>
    <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>

<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">exit_with_exception</span><span class="p">,</span> <span class="s">&#39;Registered first&#39;</span><span class="p">)</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">exit_with_exception</span><span class="p">,</span> <span class="s">&#39;Registered second&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">注册时的顺序决定了执行的顺序. 如果一个回调函数中的错误引入了另外一个错误(比他先注册但是比他后调用), 那么, 最终的信息可能对于用户来说不是最有用的. ## 这个例子, 程序首先在second上抛出异常, 但最终显示的是first异常信息,  这主要还是因为atexit回调函数不是按照注册顺序来执行的.</p>
</div>
<div class="highlight-python"><pre>$ python atexit_exception.py
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
 File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
 func(*targs, **kargs)
 File "atexit_exception.py", line 36, in exit_with_exception
 raise RuntimeError(message)
RuntimeError: Registered second
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
 File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
 func(*targs, **kargs)
 File "atexit_exception.py", line 36, in exit_with_exception
 raise RuntimeError(message)
RuntimeError: Registered first
Error in sys.exitfunc:
Traceback (most recent call last):
 File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
 func(*targs, **kargs)
 File "atexit_exception.py", line 36, in exit_with_exception
 raise RuntimeError(message)
RuntimeError: Registered first</pre>
</div>
<p>一般情况下, 你可以设置在清理函数中安静的处理和记录所有异常, 这样在程序退出时, 就不会使输出信息显得很乱.</p>
</div>
<div class="section" id="id4">
<h2>参考<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><a class="reference external" href="http://www.doughellmann.com/projects/PyMOTW/">Python Module of the Week</a></li>
<li><a class="reference external" href="http://www.doughellmann.com/downloads/PyMOTW-1.8.tar.gz">Sample Code</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="collections.html" title="PyMOTW: collections"
             >next</a> |</li>
        <li class="right" >
          <a href="commands.html" title="PyMOTW: commands"
             >previous</a> |</li>
        <li><a href="../index.html">PyMOTW Document v1.6 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 2009, vbarter &amp; liz.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.3.
    </div>
  </body>
</html>